package com.itlong.cloud.property.service.impl;

import com.itlong.cloud.POJO.DTO.property.PropertySubscriberHanlerDTO;
import com.itlong.cloud.POJO.PO.SipClusterPO;
import com.itlong.cloud.POJO.PO.SubscriberPO;
import com.itlong.cloud.PlatformConstants;
import com.itlong.cloud.datasource.dao.ISubscriberDao;
import com.itlong.cloud.operate.dao.IOperateSipClusterDao;
import com.itlong.cloud.property.service.ISubscriberService;
import com.itlong.cloud.utils.data.handler.SqlUtil;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

/**
 * <desc>
 *      sip账号服务层实现类
 * </desc>
 *
 * @createDate 2017/10/20
 */
@Service
@RefreshScope
public class SubscriberServiceImpl implements ISubscriberService {

    private static final Logger LOG = LoggerFactory.getLogger(SubscriberServiceImpl.class);

    @Autowired
    IOperateSipClusterDao iOperateSipClusterDao;

    @Autowired
    ISubscriberDao iSubscriberDao;

    @Value("${" + PlatformConstants.DEVICE_SIP_ACCOUNT_PREFIX + "}")
    public String DEVICE_SIP_ACCOUNT_PREFIX;

    /**
     * <desc>
     *      对sip数据源中的Sip账号进行添加，更新，或删除操作
     * <desc/>
     * @param   subscriberHandlerDTO    sip账号处理DTO
     * @return  Integer    添加或更新的数量
     * @author Biao.R
     * @createDate 2017/10/24
     */
    @Override
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public void saveOrUpdateSip(PropertySubscriberHanlerDTO subscriberHandlerDTO) throws Exception {
        String addUserName = DEVICE_SIP_ACCOUNT_PREFIX+subscriberHandlerDTO.getAddUserName();
        String addPassword = subscriberHandlerDTO.getAddPassword();
        String projectId = subscriberHandlerDTO.getProjectId();
        String delUserName = subscriberHandlerDTO.getDelUserName();

        if (StringUtils.isNotBlank(addUserName)) {
            if (StringUtils.isEmpty(projectId)) {
                projectId = addUserName.trim().substring(0, 8);
            }
            //获取小区的sipAddress
            SipClusterPO sipClusterPO = iOperateSipClusterDao.getSipDomainByProjectId(projectId);
            if (sipClusterPO != null) {
                SubscriberPO subscriberPO = new SubscriberPO(addUserName,StringUtils.isEmpty(addPassword)?addUserName:addPassword);
                String sipAddress = sipClusterPO.getSipAddress();
                subscriberPO.setDomain(sipAddress);
                SubscriberPO subscriber = iSubscriberDao.getByUserName(addUserName);
                if (subscriber == null) {
                    //数据库中不存在，添加
                    iSubscriberDao.save(SqlUtil.durableData(subscriberPO, PlatformConstants.TABLE_SAVE));
                } else {
                    if (!(addPassword != null && addPassword.equals(subscriber.getPassword())) || !(sipAddress != null && sipAddress.equals(subscriber.getDomain()))) {
                        //数据库中存在，并且数据不一致,则更新
                        iSubscriberDao.update(SqlUtil.durableData(subscriberPO, PlatformConstants.TABLE_UPDATE));
                    }
                }
            }else{
                LOG.info("===添加或更新sip账号失败:没有查询到该项目的Sip集群信息：addUserName：" + addUserName);
            }
        }

        //如果有需要删除的旧Sip,并且旧的sip账号和新的sip不一致，需要删除
        if (StringUtils.isNotBlank(delUserName) && !delUserName.equals(addUserName)) {
            //LOG.info("===根据username删除sip信息：delUserName：" + delUserName);
            iSubscriberDao.delSipByUserName(delUserName);
        }
    }


    /**
     * <desc>
     *      对sip数据源中的Sip账号进行添加，更新，或删除操作
     * <desc/>
     * @param   subscriberHandlerDTOs    sip账号处理DTO
     * @return  Integer    添加或更新的数量
     * @author Biao.R
     * @createDate 2017/10/24
     */
/*    @Override
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public void batchSaveOrUpdateSip(List<PropertySubscriberHanlerDTO> subscriberHandlerDTOs) throws Exception {

        if (subscriberHandlerDTOs != null && !subscriberHandlerDTOs.isEmpty()) {
            //获取项目编号，查询Sip服务器地址
            String projectId = subscriberHandlerDTOs.get(0).getProjectId();
            if (StringUtils.isNotEmpty(projectId)) {
                SipClusterPO sipClusterPO = iOperateSipClusterDao.getSipDomainByProjectId(projectId);
                if (sipClusterPO != null) {
                    String sipAddress = sipClusterPO.getSipAddress();

                    for (PropertySubscriberHanlerDTO subscriberHandlerDTO : subscriberHandlerDTOs) {
                        String addUserName = subscriberHandlerDTO.getAddUserName();
                        String addPassword = subscriberHandlerDTO.getAddPassword();
                        String delUserName = subscriberHandlerDTO.getDelUserName();
                        //添加或更新Sip数据
                        if (StringUtils.isNotEmpty(addUserName) && StringUtils.isNotEmpty(addUserName) && StringUtils.isNotEmpty(sipAddress)) {
                            SubscriberPO subscriber = iSubscriberDao.getByUserName(addUserName);
                            SubscriberPO subscriberPO = new SubscriberPO(addUserName, addPassword);
                            subscriberPO.setDomain(sipClusterPO.getSipAddress());
                            if (subscriber == null) {
                                //数据库中不存在，添加
                                iSubscriberDao.saveBuild(SqlUtil.durableData(subscriberPO, PlatformConstants.TABLE_SAVE));
                            } else {
                                //数据库中存在，更新
                                iSubscriberDao.updateBuild(SqlUtil.durableData(subscriberPO, PlatformConstants.TABLE_UPDATE));
                            }
                        }

                        //如果有需要删除的旧Sip,并且旧的sip账号和新的sip不一致，需要删除
                        if (StringUtils.isEmpty(delUserName) && !delUserName.equals(addUserName)) {
                            LOG.info("===根据username删除sip信息：delUserName：" + delUserName);
                            iSubscriberDao.delSipByUserName(delUserName);
                        }
                    }
                }
            }
        }
    }*/

}